import configService from '@/common/service/config.service.js'
const URL = 'ws://www.wan888.club:2000'
/**
 * 用法：
 * let socketTask = new SocketTask() || new SocketTask(url,method) method:'POST'
 * socketTask.setHader(Object)
 * socketTask.connect()
 * socketTask.onOpen(res => {
 * 	   socketTask.sendMsg({xx:xx,xxx:xx})
 * })	
 * socketTask.receiveMsg(res => {})
 *
 **/

class SocketTask {
	//ws 地址
	url = URL
	header = {
		'content-type': 'multipart/form-data',
	}
	method = 'POST'
	//socket是否打开
	socketOpen = false
	constructor(url, method) {
	    this.url = url,
		this.method = method
	}
	//
	setHader(header) {
		this.header = header
	}
	
	/**
	 * 连接socket
	 **/
	connect() {
		uni.connectSocket({
			url: URL,
			header: this.header,
			method: this.method,
			success: (res) => {
			}
		})
	}
	
	/**
	 * 监听打开socket
	 **/
	onOpen(callback) {
		uni.onSocketOpen((res) => {
			callback(res)
			this.socketOpen = true;
		});
	}
	
	//监听关闭socket
	onClose(callback) {
		uni.onSocketClose((res) => {
			callback(res)
			this.socketOpen = false
		});
	}
	
	//监听socket出错
	onError(callback) {
		uni.onSocketError((res) => {
			socketTask.socketOpen = false
			callback(res)
			console.error('WebSocket连接打开失败，请检查！');
		});
	}
	
	/**
	 * 发送消息
	 * @param {msg} 消息内容 
	 */
	sendMsg(msg) {
		uni.sendSocketMessage({
			data: JSON.stringify(msg)
		});
	}
	
	/**
	 * 接收消息
	 */
	receiveMsg(callback) {
		uni.onSocketMessage((res) => {
			callback(res)
		})
	}
}


export {
	URL,
	SocketTask
}